// background.ts
import { API_URL } from "./constant";
import { parseDateTimeToTs } from "./utils";

// 监听插件图标点击事件
chrome.action.onClicked.addListener(async (tab) => {
  if (!tab.id) {
    return;
  }

  try {
    await chrome.sidePanel.open({
      tabId: tab.id,
    });
  } catch (error) {
    console.error("打开侧边栏失败:", error);
    console.error("错误详情:", error instanceof Error ? error.message : error);
  }
});

function capitalizeFirstLetter(str: any) {
  if (typeof str !== "string" || str.length === 0) {
    return str; // 如果不是字符串或空字符串，直接返回
  }
  return str.charAt(0).toUpperCase() + str.slice(1);
}

async function executeSetReactInputValueBySheinShop(
  request: any,
  sender: any
): Promise<boolean> {
  return new Promise((resolve) => {
    chrome.scripting.executeScript(
      {
        target: { tabId: sender.tab.id },
        func: (tableRowDateRowKey, finallyPrice, finallyRate) => {
          return new Promise((resolveScript) => {
            const setValue = finallyRate || finallyPrice;
            const trElement = document.querySelector<HTMLElement>(
              `[data-row-key="${tableRowDateRowKey}"]`
            );
            if (!trElement) {
              resolveScript(false);
              return;
            }
            const cells = Array.from(trElement.children).filter(
              (child) =>
                child.classList.length === 1 &&
                child.classList.contains("ant-table-cell")
            );
            let inputEl;
            for (const cell of cells) {
              const group = cell.querySelector(".ant-input-group");
              if (!group) continue;

              const addon = group.querySelector(".ant-input-group-addon");
              const addonText = addon?.textContent?.trim();
              const isPercent = addonText === "%";

              if ((finallyRate && isPercent) || (!finallyRate && !isPercent)) {
                inputEl = group.querySelector<HTMLInputElement>("input");
                if (inputEl) break;
              }
            }

            if (!inputEl) {
              resolveScript(false);
              return;
            }
            const prototype = Object.getPrototypeOf(inputEl);
            const valueSetter = Object.getOwnPropertyDescriptor(
              prototype,
              "value"
            )?.set;

            if (valueSetter) {
              valueSetter.call(inputEl, setValue);
            } else {
              inputEl.value = setValue;
            }

            const inputEvent = new Event("input", {
              bubbles: true,
              cancelable: true,
            });
            inputEl.dispatchEvent(inputEvent);
            resolveScript(true);
          });
        },
        args: [request.tableRowDateRowKey, request.value, request.finallyRate],
      },
      (results) => {
        resolve(results?.[0]?.result ? true : false);
      }
    );
  });
}

async function executeSetReactInputValueBySheinPlatform(
  request: any,
  sender: any
): Promise<boolean> {
  return new Promise((resolve) => {
    chrome.scripting.executeScript(
      {
        target: { tabId: sender.tab.id },
        func: (skuCode, value) => {
          return new Promise((resolveScript) => {
            // 基于 SKU 文本在表格中定位行
            const rows = document.querySelectorAll(
              ".so-table-table-bordered .so-table-normal"
            );
            let trElement: HTMLElement | null = null;
            for (const row of Array.from(rows)) {
              const skuEl = row.querySelector('[class*="mrs_styles__sku--"]');
              const text = skuEl?.textContent || "";
              const match = text.match(/SKU:\s([a-zA-Z0-9]+)/);
              if (match && match[1] === skuCode) {
                trElement = row as HTMLElement;
                break;
              }
            }
            if (!trElement) {
              resolveScript(false);
              return;
            }
            const inputTdEl: HTMLTableCellElement | null =
              trElement.querySelector(".so-input-group");
            const inputEl = inputTdEl?.querySelector<HTMLInputElement>("input");
            if (!inputEl) {
              resolveScript(false);
              return;
            }
            const prototype = Object.getPrototypeOf(inputEl);
            const valueSetter = Object.getOwnPropertyDescriptor(
              prototype,
              "value"
            )?.set;

            if (valueSetter) {
              valueSetter.call(inputEl, value);
            } else {
              inputEl.value = value;
            }

            const inputEvent = new Event("input", {
              bubbles: true,
              cancelable: true,
            });
            inputEl.dispatchEvent(inputEvent);
            resolveScript(true);
          });
        },
        args: [request.skuCode, request.value],
      },
      (results) => {
        resolve(results?.[0]?.result ? true : false);
      }
    );
  });
}

const goodsPayloadObjMap: Record<string, any> = {
  selfPlatform: null,
  semiPlatform: null,
};
const checkActivityPayloadObjMap: Record<string, any> = {
  selfPlatform: null,
  semiPlatform: null,
};

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "getSkuPrice") {
    const params = {
      ...(request.data || {}),
    };
    const queryParams = new URLSearchParams(params).toString();
    fetch(
      `${API_URL}/api/goods-launch-${
        request.platform
      }/commonData/selectList/launchCollectProductSkuRecord${capitalizeFirstLetter(
        request.platform
      )}?${queryParams}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + request.token,
        },
      }
    )
      .then((res) => res.json())
      .then((data) => sendResponse(data))
      .catch((err) => sendResponse({ error: err.message }));
    return true; // 保持消息通道开放
  } else if (request.type === "setReactInputValueBySheinShop") {
    // 使用异步执行
    executeSetReactInputValueBySheinShop(request, sender)
      .then((success) => {
        sendResponse({ success });
      })
      .catch((error) => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  } else if (request.type === "setReactInputValueBySheinPlatform") {
    // 使用异步执行
    executeSetReactInputValueBySheinPlatform(request, sender)
      .then((success) => {
        sendResponse({ success });
      })
      .catch((error) => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  } else if (request.type === "getSelfPlatformAddGoodsApiPayload") {
    sendResponse(goodsPayloadObjMap.selfPlatform);
  } else if (request.type === "getSemiPlatformAddGoodsApiPayload") {
    sendResponse(goodsPayloadObjMap.semiPlatform);
  } else if (request.type === "getSemiPlatformCreateActivePayload") {
    try {
      const { semiPlatform: semiPlatformGoodsPayloadObj } = goodsPayloadObjMap;
      const { semiPlatform: semiPlatformCheckActivityPayloadObj } =
        checkActivityPayloadObjMap;
      if (
        semiPlatformGoodsPayloadObj &&
        Object.keys(semiPlatformGoodsPayloadObj).length > 0 &&
        semiPlatformCheckActivityPayloadObj &&
        Object.keys(semiPlatformCheckActivityPayloadObj).length > 0
      ) {
        const {
          act_name,
          activity_rule,
          ref_tool_id,
          time_zone,
          zone_end_time,
          zone_start_time,
        } = semiPlatformCheckActivityPayloadObj;
        const { activity_base_info_request } = semiPlatformGoodsPayloadObj;
        const { sub_type_id } = activity_base_info_request;
        sendResponse({
          activity_base_info_request: {
            act_name,
            activity_rule,
            ref_tool_id,
            time_zone,
            zone_end_time,
            zone_start_time,
            sub_type_id,
            notify_flag: 1, // 活动规则中的《活动结束时通知我》取不到值，默认通知
          },
          pricing_type: 2, // 没找到这个的赋值，看起来默认都是2
        });
      }
    } catch {
      sendResponse();
    }
  } else if (request.type === "getSelfPlatformCreateActivePayload") {
    try {
      const { selfPlatform: selfPlatformCheckActivityPayloadObj } =
        checkActivityPayloadObjMap;
      if (
        selfPlatformCheckActivityPayloadObj &&
        Object.keys(selfPlatformCheckActivityPayloadObj).length > 0
      ) {
        const {
          pricing_type,
          ref_tool_id,
          sale_site,
          sub_type_id,
          time_zone,
          zone_end_time,
          zone_start_time,
        } = selfPlatformCheckActivityPayloadObj;
        sendResponse({
          pricing_type,
          ref_tool_id,
          sale_site,
          sub_type_id,
          time_zone,
          zone_end_time,
          zone_start_time,
          operate_type: 2,
        });
      }
    } catch {
      sendResponse();
    }
  }
});

function parseRequestBody(details: any) {
  let payloadObjMap;
  if (details.requestBody) {
    // 表单体 formData 优先：Chrome 会把 x-www-form-urlencoded 映射为 formData
    if (details.requestBody.formData) {
      const formData = details.requestBody.formData as Record<
        string,
        string[] | string
      >;
      const obj: Record<string, any> = {};
      for (const key of Object.keys(formData)) {
        const value = (formData as any)[key];
        obj[key] = Array.isArray(value)
          ? value.length === 1
            ? value[0]
            : value
          : value;
      }
      payloadObjMap = obj;
    } else if (details.requestBody.raw && details.requestBody.raw.length > 0) {
      // 原始字节体 raw：可能是 JSON 或 urlencoded
      const decoder = new TextDecoder("utf-8");
      const chunks: string[] = [];
      for (const part of details.requestBody.raw) {
        if (part.bytes) {
          const text = decoder.decode(part.bytes);
          if (text) chunks.push(text);
        }
      }
      const bodyText = chunks.join("");
      if (bodyText) {
        try {
          payloadObjMap = JSON.parse(bodyText);
        } catch {
          try {
            const params = new URLSearchParams(bodyText);
            const obj: Record<string, any> = {};
            params.forEach((v, k) => {
              if (obj[k] === undefined) {
                obj[k] = v;
              } else if (Array.isArray(obj[k])) {
                (obj[k] as any[]).push(v);
              } else {
                obj[k] = [obj[k], v];
              }
            });
            payloadObjMap = obj;
          } catch {
            payloadObjMap = { raw: bodyText };
          }
        }
      }
    }
  }

  return payloadObjMap;
}

chrome.webRequest.onBeforeRequest.addListener(
  function (details: any) {
    // 商品搜索
    if (
      [
        "mrs-api-prefix/promotion/limited/query_goods",
        "mrs-api-prefix/promotion/simple_platform/query_goods",
      ].some((url) => details.url.includes(url))
    ) {
      const semiUrls = ["mrs-api-prefix/promotion/simple_platform/query_goods"];
      const isSemi = semiUrls.some((url) => details.url.includes(url));
      const field = isSemi ? "semiPlatform" : "selfPlatform";
      try {
        if (details.method !== "POST") {
          return;
        }

        const payloadObj = parseRequestBody(details);
        if (payloadObj) {
          goodsPayloadObjMap[field] = payloadObj;
        }
      } catch (e) {
        // 忽略错误
      }
    } else if (
      [
        "mrs-api-prefix/promotion/simple_platform/check_activity",
        "mrs-api-prefix/promotion/limited/check_activity",
      ].some((url) => details.url.includes(url))
    ) {
      const semiUrls = [
        "mrs-api-prefix/promotion/simple_platform/check_activity",
      ];
      const isSemi = semiUrls.some((url) => details.url.includes(url));
      const field = isSemi ? "semiPlatform" : "selfPlatform";
      try {
        if (details.method !== "POST") {
          return;
        }

        const payloadObj = parseRequestBody(details);
        if (payloadObj) {
          checkActivityPayloadObjMap[field] = payloadObj;
        }
      } catch (e) {
        // 忽略错误
      }
    }
  },
  { urls: ["*://*.shein.com/*", "*://*.geiwohuo.com/*"] },
  ["requestBody"]
);
